<?php
namespace Common\Logic;

use Common\Model\UserCourseModel;

class UserCourseLogic extends UserCourseModel
{
    /*
     * Function:        getUserCourseList
     * Description:    用户课程列表
     * @param:        $page string 起始页
    $filter array 过滤数组
    $pageSize string 每页显示条数
     */
    public function getUserCourseList($page = 1, $filter = '', $pageSize = 20)
    {
        $conditon = $this->getUserCourseFilter($filter);
        return $this->alias('a')->join('left join course b on a.course_id=b.id')->field('a.*,b.title,b.cate_id,b.nums as all_nums,b.t_nums,b.begin_time,b.end_time,b.course_date,b.coach_id,b.classroom_id,b.level')->where($conditon)->order('a.id desc')->limit(($page - 1) * $pageSize, $pageSize)->select();
    }

    /*
     * Function:get:    getUserCourseFilter
     * Description:    用户课程列表搜索过滤项
     * @param:        $filter array 过滤数组
     */
    public function getUserCourseFilter($filter = '')
    {
        $conditon = array();
        $conditon['a.is_deleted'] = 0;
        if (!empty($filter['status'])) {
            $conditon['a.status'] = $filter['status'];
        }
        if (!empty($filter['user_id'])) {
            $conditon['a.user_id'] = $filter['user_id'];
        }
        if (!empty($filter['user_name'])) {
            $userIdData = M('user')->where(['username' => ['like', '%' . $filter['user_name'] . '%']])->getField('id', true);
            if (!empty($userIdData)) {
                $conditon['a.user_id'] = ['in', $userIdData];
            }
        }
        if (!empty($filter['mobile'])) {
            $userId = M('user')->where(['mobile' => $filter['mobile']])->getField('id');
            if (!empty($userId)) {
                $conditon['a.user_id'] = $userId;
            }
        }
        if (!empty($filter['store_id'])) {
            $conditon['a.store_id'] = $filter['store_id'];
        }
        if (!empty($filter['cate_id'])) {
            $conditon['b.cate_id'] = $filter['cate_id'];
        }
        if (!empty($filter['title'])) {
            $conditon['b.title'] = array('like', '%' . $filter['title'] . '%');
        }
        if (!empty($filter['course_id'])) {
            $conditon['a.course_id'] = $filter['course_id'];
        }
        if (!empty($filter['coach_id'])) {
            $conditon['b.coach_id'] = $filter['coach_id'];
        }
        if (!empty($filter['addtime_fromdate']) || !empty($filter['addtime_todate'])) {
            if (!empty($filter['addtime_fromdate']) && !empty($filter['addtime_todate'])) {
                $conditon['a.addtime'] = array(array('egt', $filter['addtime_fromdate']), array('elt', $filter['addtime_todate']));
            } else if (!empty($filter['addtime_fromdate'])) {
                $conditon['a.addtime'] = array('egt', $filter['addtime_fromdate']);
            } else if (!empty($filter['addtime_todate'])) {
                $conditon['a.addtime'] = array('elt', $filter['addtime_todate']);
            }
        }
        return $conditon;
    }

    /*
     * Function:get:    getUserCourseCount
     * Description:    用户课程列表总数
     * @param:        $filter array 过滤数组
     */
    public function getUserCourseCount($filter = '')
    {
        $conditon = $this->getUserCourseFilter($filter);
        return $this->alias('a')->join('left join course b on a.course_id=b.id')->field('a.*,b.title,b.cate_id,b.nums,b.t_nums,b.begin_time,b.end_time')->where($conditon)->count();
    }

    /*
     * Function:        addUserCourse
     * Description:    增加用户课程
     * @param:        $data array 增加的数组
     */
    public function addUserCourse($data)
    {
        return $this->add($data);
    }

    /*
     * Function:        getUserCourseInfo
     * Description:    获取用户课程信息 by row
     * @param:        $id int ID
     */
    public function getUserCourseInfo($id)
    {
        return $this->where(array('id' => $id))->find();
    }

    /*
     * Function:        updateUserCourse
     * Description:    更新用户课程
     * @param:        $data array 更新的数组
     */
    public function updateUserCourse($data)
    {
        return $this->save($data);
    }

    /*
     * Function:        deleteUserCourse
     * Description:    删除用户课程
     * @param:        $id int ID
     */
    public function deleteUserCourse($id)
    {
        return $this->where(array('id' => $id))->delete();
    }

    public function cancelUserCourse($id = '', $flag = 1)
    {
        $user_course_info = M('user_course')->find($id);
        if (!$user_course_info || !in_array($user_course_info['status'], [1, 3])) {
            $ret = array('code' => 0, 'message' => '该课程不可取消!');
            return $ret;
        }
        if (!$rsInfo = D('User')->getUserInfo($user_course_info['user_id'])) {
            $return['code'] = 0;
            $return['message'] = '此用户不存在';
            return $return;
        }
        if (!$course_info = D('Course')->getCourseInfo($user_course_info['course_id'])) {
            $return['code'] = 0;
            $return['message'] = '该课程不存在';
            return $return;
        }
        if (!empty($flag)) {
            $now = time();
            $begin_time = strtotime($course_info['course_date'] . ' ' . $course_info['begin_time']);
            $can_queue_time = ($begin_time - $now) / 60; //距离开始时间所剩分钟数
            $today = date('Y-m-d');
            if ($today == $course_info['course_date']) {
                if ($can_queue_time < $course_info['cancel_time']) {
                    $return['code'] = 0;
                    $return['errorMsg'] = '该课程过可取消时间';
                    return $return;
                }
            }
        }
        if (empty($flag)) {
            $ret = M('user_course')->where(['id' => $id])->save(['is_system_cancel' => 1, 'status' => 5, 'cancel_time' => date('Y-m-d H:i:s')]);
        } else {
            $ret = M('user_course')->where(['id' => $id])->save(['status' => 5, 'cancel_time' => date('Y-m-d H:i:s')]);
        }
        if ($ret === false) {
            return ['code' => 0, 'message' => '用户课程更新失败'];
        }
        if ($user_course_info['status'] == 1) {
            $ret = M('user_card')->where(['id' => $user_course_info['user_card_id']])->setDec('freez', ($user_course_info['nums'] * $course_info['card_nums']));
            if ($ret === false) {
                return ['code' => 0, 'message' => '用户卡更新失败'];
            }
        }
        //查看有没有预备的人
        if (!empty($course_info['t_nums'])) {
            $queueData = M('user_course')->where(['store_id' => $course_info['store_id'], 'course_id' => $course_info['id'], 'status' => 3, 'is_deleted' => 0, 'nums' => ['gt', $user_course_info['nums']]])->find();
            if (!empty($queueData)) {
                $data = [];
                $data['id'] = $queueData['course_id'];
                $data['nums'] = $queueData['nums'];
                $data['user_id'] = $queueData['user_id'];
                $data['memo'] = $queueData['memo'];
                $ret = D('Course')->yuYueCourse($data, 1);
                if ($ret['code'] == 0) {
                    $ret['errorMsg'] = $ret['message'];
                    return $ret;
                }
            }
        }
        $ret = array('code' => 1, 'message' => '操作成功');
        return $ret;
    }

    public function signCourse($id = '', $flag = '')
    {
        $user_course_info = M('user_course')->find($id);
        if (!$user_course_info || !in_array($user_course_info['status'], [1])) {
            $ret = array('code' => 0, 'message' => '该课程无法签到!');
            return $ret;
        }
        if (!$rsInfo = D('User')->getUserInfo($user_course_info['user_id'])) {
            $return['code'] = 0;
            $return['message'] = '此用户不存在';
            return $return;
        }
        if (!$course_info = D('Course')->getCourseInfo($user_course_info['course_id'])) {
            $return['code'] = 0;
            $return['message'] = '该课程不存在';
            return $return;
        }
        //已预约人数
        $yuYueNums = M('user_course')->where(['status' => 1, 'course_id' => $course_info['id'], 'is_deleted' => 0])->sum('nums');
        // if(($yuYueNums-$course_info['nums'])<0){
        //     $return['code'] = 0;
        //     $return['message'] = '还未约满，无法操作签到';
        //     return $return;
        // }
        if (!$card_info = D('UserCard')->getUserCardInfo($user_course_info['user_card_id'])) {
            $return['code'] = 0;
            $return['message'] = '该会员卡不存在';
            return $return;
        }
        $ret = M('user_course')->where(['id' => $id])->save(['status' => 2, 'sign_time' => date('Y-m-d H:i:s')]);
        if ($ret === false) {
            return ['code' => 0, 'message' => '用户课程更新失败'];
        }
        $data = [
            'freez' => ['exp', 'freez - ' . ($user_course_info['nums'] * $course_info['card_nums'])],
            'nums' => ['exp', 'nums - ' . ($user_course_info['nums'] * $course_info['card_nums'])],
        ];
        $ret = M('user_card')->where(['id' => $user_course_info['user_card_id']])->save($data);
        if ($ret === false) {
            return ['code' => 0, 'message' => '用户卡更新失败'];
        }
        //已签到人数
        $signNums = M('user_course')->where(['status' => 2, 'course_id' => $course_info['id'], 'is_deleted' => 0])->sum('nums');
        if (($course_info['nums'] - $signNums - $user_course_info['nums']) <= 0) {
            M('course')->where(['id' => $course_info['id']])->save(['status' => 2, 'complete_time' => date('Y-m-d H:i:s', time())]);
        }
        //卡操作记录
        $logData = [];
        $logData['store_id'] = $user_course_info['store_id'];
        $logData['tid'] = $user_course_info['user_card_id'];
        $logData['user_id'] = $rsInfo['id'];
        $logData['type'] = 2;
        $logData['nums'] = $user_course_info['nums'] * $course_info['card_nums'];
        $logData['now_nums'] = $card_info['nums'];
        if (!empty($flag)) {
            $logData['memo'] = '教练操作签到';
        } else {
            $logData['memo'] = '后台操作签到';
        }
        if (!D('UserCardLogs')->addUserCardLogs($logData)) {
            return ['code' => 0, 'message' => '卡操作记录增加失败'];
        }
        $ret = array('code' => 1, 'message' => '操作成功');
        return $ret;
    }

    /*
     * Function: exportUserCourse
     * Description:导出课程信息
     * @param:$filter array 过滤条件数组
     */
    public function exportUserCourse($filter = '')
    {
        ini_set('memory_limit', '512M');
        $fileName = 'userCourse';
        $supplierFlag = 1;
        $headArr = array('所属场馆',
            '课程',
            '教练',
            '教室',
            '用户',
            '预约次数',
            '状态',
            '预约时间',
        );
        $conditon = $this->getUserCourseFilter($filter);
        $result = $this->alias('a')->join('left join course b on a.course_id=b.id')->where($conditon)->order('a.id desc')->select();
        if (is_array($result) && count($result) > 0) {
            foreach ($result as $key => $val) {
                $val['store_name'] = M('stores_list')->where(['id' => $val['store_id']])->getField('title');
                $val['user_name'] = M('user')->where(['id' => $val['user_id']])->getField('username');
                $val['coach_name'] = M('stores_worker_list')->where(['id' => $val['coach_id'], 'role' => 1])->getField('name');
                $val['classroom_name'] = M('stores_classroom_list')->where(['id' => $val['classroom_id']])->getField('name');
                $val['status'] = $this->switchUserCourseStatus($val['status']);
                $sdata = array(
                    $val['store_name'],
                    $val['title'],
                    $val['coach_name'],
                    $val['classroom_name'],
                    $val['user_name'],
                    $val['nums'],
                    $val['status'],
                    $val['addtime'],
                );
                $data[] = $sdata;
            }
            getExcel($fileName, $headArr, $data);
        }
    }

    public function switchUserCourseStatus($status = '')
    {
        $name = '';
        switch ($status) {
            case 1:
                $name = '已预约';
                break;
            case 2:
                $name = '已订';
                break;
            case 3:
                $name = '排队';
                break;
            case 4:
                $name = '请假';
                break;
            case 5:
                $name = '取消';
                break;
            default:
                $name = '未预约';
                break;
        }
        return $name;
    }
}
